var express = require('express');
var router = express.Router();
var sql = require('./../tool/sql');

router.get('/', function(req, res, next) {
  sql.sort('pushup', {}, {_id: 0}, {run: -1}).then(data => {
    console.log(data)
    res.send(data)
  }).catch(err => console.log(err))
});
router.get('/paging', function(req, res, next) {
  const pageCode = req.query.pageCode * 1 || 1;
  const limitNum = req.query.limitNum * 1 || 5;
  sql.paging('pushup', pageCode, limitNum, { run: -1 }).then(data => {
    console.log(data)
    res.send(data)
    
  }).catch(err => console.log(err))
});

router.get('/section', function(req, res, next) {
  const min = req.query.min * 1;
  const max = req.query.max * 1;
  const pageCode = 1;
  sql.find('pushup', { run: {$lte: max, $gte: min} }, {}).then(data => {
    console.log(data)
    // res.send(data)
    res.send(data)
  }).catch(err => console.log(err))
});
router.get('/add', function(req, res, next) {
  let insertData = req.query; // req.query  --- {username:'', run: ''}
  insertData.run *= 1
  sql.insert('pushup', insertData).then(() => {
    // res.send(insertData)
    // res.redirect('/pushup')
    res.send(1)
  }).catch(err => console.log(err))
});

router.get('/delete', function(req, res, next) {
  const deleteData = req.query; // req.query  --- {username:''}
  sql.remove('pushup', deleteData).then(() => {
    // res.send(insertData)
    // res.redirect('/pushup')
    res.send(1)
  }).catch(err => console.log(err))
});
router.get('/updateOne', function(req, res, next) {
  let obj = req.query; // req.query  --- {username:'', run: 2}
  obj.run *= 1
  const whereData = { username: obj.username };
  const updateData = {
    $set: obj
  }
  sql.updateOne('pushup', whereData, updateData).then(() => {
    // res.redirect('/pushup')
    res.send(1)
  }).catch(err => console.log(err))
});
router.get('/updateMany', function(req, res, next) {
  const obj = req.query; // req.query  --- {username:'', run: 2}
  const whereData = { run: {$gt: 0}};
  const num = obj.num * 1;
  const updateData = {
    $inc: {run: +num}
  }
  sql.updateMany('pushup', whereData, updateData).then(() => {
    // res.redirect('/pushup')
    res.send(1)
  }).catch(err => console.log(err))
});

router.get('/search', function (req, res, next) {
  const obj = req.query; // {username:''}
  sql.find('pushup', {username: eval('/' + obj.username + '/')}, {}).then(data => {
    console.log(data)
    res.send(data)
  })
})
router.get('/run', function (req, res, next) {
  let obj = req.query; // {num:''}
  obj.num *= 1;
  var arr = [];
  arr.push(obj.num)
  sql.find('pushup', {run: obj.num}, {}).then(data => {
    console.log(data)
    // res.send(data)
    res.send(data)
  })
})
router.get('/kind', function (req, res, next) {
  const obj = req.query; // {username:''}
  sql.distinct('pushup', 'run').then(data => {
    res.send(data)
  });
})
module.exports = router;
